﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using WpfClient.DataFeedService;

namespace WpfClient
{
    public class DataFeedSubscriber : IMarketDataCallback, IDisposable, INotifyPropertyChanged
    {
        private string id;
        private MarketDataClient client;

        private double price;
        private string delay;

        public DataFeedSubscriber()
        {
            ID = new Random().Next(1000000).ToString();

            InstanceContext context = new InstanceContext(this);
            client = new MarketDataClient(context);
        }

        public String ID
        {
            get { return id; }
            set { id = value; }
        }

        public double Price
        {
            get { return price; }
            set { price = value; OnPropertyChanged("Price"); }
        }

        public String Delay
        {
            get { return delay; }
            set { delay = value; OnPropertyChanged("Delay"); }
        }

        public void Dispose()
        {
            try
            {
                client.Unsubscribe();
                client.Close();
            }
            catch { }
        }

        public void SendTickUpdate(TickUpdate update)
        {
            Price = update.Price;

            Delay = (DateTime.Now - update.Timestamp).ToString(@"ss\.fffffff");
        }

        public void Subscribe()
        {
            client.Subscribe();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                this.PropertyChanged(this, e);
            }
        }

        public override string ToString()
        {
            return Price.ToString();
        }
    }
}
